import { type ComponentInternalInstance, nextTick, type Ref } from "vue";

export class Instance {
    protected instance: ComponentInternalInstance = {} as ComponentInternalInstance;
    public mounted = ({ componentInstance, setReflectInstance }: { componentInstance: ComponentInternalInstance, setReflectInstance: (cs: Instance) => void }) => {
        this.instance = componentInstance;
        setReflectInstance && setReflectInstance(this)
    }

    protected getInstance() {
        return this.instance;
    }

    public getExposed = async () => {
        await nextTick()
        return this.instance.exposed as Record<string, any>
    }
}


export const getReflectInstance = <T>(emits: (event: "mounted", payload: { componentInstance: any, setReflectInstance: (cs: T) => void }) => void) => {
    // 使用const和ref来创建一个不可变的ref实例
    const reflectInstance: Ref<T | undefined> = ref<T>()

    try {
        // 通过精确的类型定义，确保payload中的属性符合预期
        emits('mounted', {
            componentInstance: getCurrentInstance(),
            setReflectInstance: (cs: T) => {
                // 由于T现在是受约束的，这里可以提高类型安全性
                reflectInstance.value = cs
            }
        })
    } catch (error) {
        // 异常处理：可以根据需要记录错误或执行其他错误处理逻辑
        console.error("Error occurred while emitting 'mounted' event:", error)
    }

    // 由于reflectInstance可能还没有被设置，这里返回undefined | T来反映这一点
    // 如果确定reflectInstance在调用前一定会被设置，可以去掉|undefined
    return reflectInstance.value as T
}